import re

from django.newforms.widgets import Widget, Select
from django.utils.dates import MONTHS


class SelectTimeWidget(Widget):
	"""
	A Widget that displays time input as a <select> box in 30 min increments.
	"""
	time_field = '%s_time'

	def render(self, name, value, attrs=None):
		# output - an array of strings containing the HTML for this widget
		output = []
		
		# time_choices - an array of tuples in the format (value, text)
		#	These tuples are used to populate the <select> box generated by
		#   this widget.
		#
		# 	value - the value returned to the server (24hr format)
		#	text - the value displayed to the user in the <select> box (12hr)
		time_choices = []
		
		# start at 12:00am
		time_choices.append(("00:00", "12:00am"))
		time_choices.append(("00:30", "12:30am"))
		
		# do range 1:00am to 11:30pm
		for hour_24 in range(1,24):
			
			isAM = (hour_24 < 12)
			ampm = "am" if isAM else "pm"
			
			hour_12 = str(hour_24 if (hour_24 <= 12) else (hour_24 - 12))
			hour_24 = str(hour_24)
			
			time_choices.append((hour_24 + ":00", hour_12 + ":00" + ampm))
			time_choices.append((hour_24 + ":30", hour_12 + ":30" + ampm))

		select_html = Select(choices=time_choices).render(self.time_field % name, value)
		output.append(select_html)
		
		return u'\n'.join(output)

	def value_from_datadict(self, data, name):
		return data.get(self.time_field % name)

